package com.springapi.controller;

import com.github.pagehelper.PageInfo;
import com.springapi.entity.Maillist;
import com.springapi.entity.Setting;
import com.springapi.entity.Shop;
import com.springapi.entity.Users;
import com.springapi.service.MaillistService;
import com.springapi.service.SettingService;
import com.springapi.service.ShopService;
import com.springapi.utils.Sendsms;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 快递列表(Maillist)表控制层
 *
 * @author makejava
 * @since 2025-01-13 20:37:13
 */
@RestController
@RequestMapping("/api/maillist")
public class MaillistController {
    /**
     * 服务对象
     */
    @Resource
    private MaillistService maillistService;

    @Resource
    private SettingService settingService;


    @Resource
    private ShopService shopService;



    //通过appid和shopid查询店铺未出库包裹
    @GetMapping("/findbynoout")
    public Integer findbynoout(@RequestParam int appid, @RequestParam int shopid) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        return maillistService.findbynoout(appid,shopid);
    }

    //通过appid和shopid查询店铺全部包裹
    @GetMapping("/findbyin")
    public Integer findbyin(@RequestParam int appid, @RequestParam int shopid) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        return maillistService.findbyin(appid,shopid);
    }

    //通过appid和shopid查询店铺指定时间段入库包裹数量
    @GetMapping("/findbyintime")
    public Integer findbyintime(@RequestParam int appid, @RequestParam int shopid, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date intime1, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date intime2 ) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        return maillistService.findbyintime(appid,shopid,intime1,intime2);
    }

    //通过appid和shopid查询店铺指定时间段出库包裹数量
    @GetMapping("/findbyouttime")
    public Integer findbyouttime(@RequestParam int appid,@RequestParam int shopid,@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date outtime1,@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date outtime2  ) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        return maillistService.findbyouttime(appid,shopid,outtime1,outtime2);
    }

    //通过appid和shopid查询店铺超过入库时间多少天没有出库的异常件数量
    @GetMapping("/findbyabnormal")
    public Integer findbyabnormal(@RequestParam int appid,@RequestParam int shopid,@RequestParam Integer days   ) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        return maillistService.findbyabnormal(appid,shopid,days);
    }



    /**
     * 通过appid和shopid查询店铺发送短信失败的包裹
     */
    @GetMapping("/findlistbysendmsg")
    public List<Maillist> findlistbysendmsg(@RequestParam int appid,@RequestParam int shopid  ) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        return maillistService.findlistbysendmsg(appid,shopid);
    }

    //通过appid和shopid查询店铺超过入库时间多少天没有出库的异常件
    @GetMapping("/findlistbyabnormal")
    public List<Maillist> findlistbyabnormal(@RequestParam int appid,@RequestParam int shopid,@RequestParam Integer days   ) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        return maillistService.findlistbyabnormal(appid,shopid,days);
    }

    //包裹重发短信
    @GetMapping("/mailsenmsg")
    public String mailsenmsg(@RequestParam int mailid ) {
        String res="短息发送失败";

        try {
            //第一步，先根据id获取对应包裹
            Maillist m= maillistService.queryById(mailid);

            //第二步，获取包裹相对于店铺信息
            Shop s= shopService.queryById(m.getShopid());

            //第三步，组装短信内容
            String dxcontent="【消息中心】取货码"+m.getPkcodestr()+"，您有包裹已到"+s.getShopaddress()+s.getName();
            String sendsmsres=  Sendsms.doSendsms(m.getMobile(),dxcontent);
            if(sendsmsres.equals("ok")){
                System.out.println("短信发送成功");
                //如果账户短信条数大于0 短信条数-1
                s.setDxnumber(s.getDxnumber()-1);
                shopService.update(s);
                m.setIssendmsg("是");
                maillistService.update(m);
                res="短信发送成功";
            }else{
                System.out.println("短信发送失败");
                m.setIssendmsg("否");
                maillistService.update(m);
            }


        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return  res;

    }
    //根据条件查询快递
    @GetMapping("/myfindAll")
    public PageInfo<Maillist> myfindAll(@RequestParam int appid,@RequestParam int shopid ,@RequestParam int page,@RequestParam int size,@RequestParam String isout ,@RequestParam String waybill ,@RequestParam String pkcodestr ,@RequestParam String name ,@RequestParam String mobile) {
        System.out.println("appid:"+appid);
        System.out.println("shopid:"+shopid);
        if(isout.isEmpty() || isout==""){
            isout="";
        }
        if(waybill.isEmpty() || waybill==""){
            waybill="";
        }
        if(name.isEmpty() || name==""){
            name="";
        }
        if(mobile.isEmpty() || mobile==""){
            mobile="";
        }

        if(pkcodestr.isEmpty() || pkcodestr==""){
            pkcodestr="";
        }

        return this.maillistService.myfindAll(appid,shopid,page,size,isout,waybill,pkcodestr,name,mobile);
    }

    /**
     * 分页查询
     *
     * @param maillist 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Maillist>> queryByPage(Maillist maillist, PageRequest pageRequest) {
        return ResponseEntity.ok(this.maillistService.queryByPage(maillist, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Maillist> queryById(@PathVariable("id") Integer id) {



        return ResponseEntity.ok(this.maillistService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param maillist 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Maillist> add(@RequestBody Maillist maillist) {
        Maillist res= null;
        System.out.println("appid========:"+maillist.getAppid());
        System.out.println("shopid=======:"+maillist.getShopid());
        try {
            //获取商户信息，主要是获取商户位置和电话，用于之后发短信
            Shop s= shopService.queryById(maillist.getShopid());
            //获取商户设置，是否发送短信设置
            List<Setting>  issend= settingService.findshopsettingbyname(maillist.getAppid(),maillist.getShopid(),"是否发送短信");
            //根据运单号查询包裹是否已入库
            List<Maillist> m= this.maillistService.findbywaybill(maillist.getAppid(),maillist.getShopid(),maillist.getWaybill());

            //如果包裹未入库，开始新增入库操作
            if(m ==null || m.size()==0 || m.isEmpty()){
                System.out.println("新增开始");
                //获取新收件码
                Integer pkcode=maillistService.getnewpkcode(maillist.getAppid(),maillist.getShopid(),maillist.getShelfnumber());
                System.out.println("生成最新收件码："+pkcode);
                maillist.setPkcode(pkcode);

                String pkcodestr="";
                if(pkcode<10){
                    pkcodestr=maillist.getShelfnumber()+"-"+"000"+pkcode;
                }else if(pkcode>=10 && pkcode<100){
                    pkcodestr=maillist.getShelfnumber()+"-"+"00"+pkcode;
                }else if(pkcode>=100 && pkcode<1000){
                    pkcodestr=maillist.getShelfnumber()+"-"+"0"+pkcode;
                }else{
                    pkcodestr=maillist.getShelfnumber()+"-"+pkcode;
                }


                maillist.setPkcodestr(pkcodestr);

                res=this.maillistService.insert(maillist);
                String a=maillist.getMobile();
                if (!a.contains("*") && !a.matches(".*\\p{IsHan}.*") && a.matches("\\d{11}")) {

                    if(!s.getShopaddress().isEmpty() && !s.getShopphone().isEmpty()){
                        //如果商户设置配置了发送收件码短信
                        if(issend.get(0).getValue().equals("是") ){
                            System.out.println("后台设置：需要发短信");
                            //如果商户短信条数大于0
                            if(s.getDxnumber() >0){
                                //String dxcontent="【消息中心】取货码"+pkcodestr+"，您有包裹已到"+s.getShopaddress()+s.getName()+"联系电话："+s.getShopphone();
                                String dxcontent="【消息中心】取货码"+pkcodestr+"，您有包裹已到"+s.getShopaddress()+s.getName();
                                String sendsmsres=  Sendsms.doSendsms(maillist.getMobile(),dxcontent);
                                if(sendsmsres.equals("ok")){
                                    System.out.println("短信发送成功");
                                    //如果账户短信条数大于0 短信条数-1
                                    s.setDxnumber(s.getDxnumber()-1);
                                    shopService.update(s);
                                    res.setIssendmsg("是");
                                    maillistService.update(res);
                                }else{
                                    System.out.println("短信发送失败");
                                    res.setIssendmsg("否");
                                    maillistService.update(res);
                                }
                            }else{
                                System.out.println("短信发送失败");
                                res.setIssendmsg("否");
                                maillistService.update(res);
                            }


                        }else{
                            System.out.println("后台设置：不需要发短信");

                        }
                    }else{
                        System.out.println("店铺设置有问题，地址或者手机号为空");
                        res.setIssendmsg("否");
                        maillistService.update(res);
                    }



                }


            }else{
                // 如果包裹已入库，设置res为null返回给平台
                System.out.println("拒绝新增，根据运单号已在数据库找到包裹");
            }

        } catch (Exception e) {

            System.out.println("系统异常:"+e.getMessage());
            //res=this.maillistService.insert(maillist);

        }
        return ResponseEntity.ok(res);
    }

    /**
     * 编辑数据
     *
     * @param maillist 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Maillist> edit(@RequestBody Maillist maillist) {
        return ResponseEntity.ok(this.maillistService.update(maillist));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.maillistService.deleteById(id));
    }

}

